<template>
  <div class="review-topic">
    <InnerBreadcrumb v-model="indexKey" :path="breadPath" :showBack="true"/>
    <div class="edu-page-warp" v-show="indexKey == 1">
      <condition-card @reset="reset" @search="searchList" label-width="140px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="毕业年份">
              <el-date-picker
                class="search-item"
                :clearable="false"
                v-model="queryForm.condition.grade"
                @change="handleGradeChange"
                value-format="yyyy"
                type="year"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行政学院">
              <el-select
                v-model="queryForm.condition.faculty"
                filterable
                @change="handleCollegeChange"
                class="search-item"
                clearable
              >
                <el-option
                  v-for="item in source.studentColleges"
                  :key="item.collegeId"
                  :label="item.collegeIdI18n"
                  :value="item.collegeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业">
              <el-select
                v-model="queryForm.condition.subject"
                filterable
                class="search-item"
                clearable
              >
                <el-option
                  v-for="item in source.subjectOptions"
                  :key="item.subjectId"
                  :label="item.subjectName"
                  :value="item.subjectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务书状态">
              <el-select
                v-model="queryForm.condition.status"
                filterable
                class="search-item"
                clearable
              >
                <el-option
                  v-for="item in source.statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课题性质">
              <el-select
                v-model="queryForm.condition.subjectProperties"
                filterable
                class="search-item"
                clearable
              >
                <el-option
                  v-for="item in source.subjectNatureOptions"
                  :key="item.id"
                  :label="item.subjectProperties"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="课题名称">
              <el-input
                v-model="queryForm.condition.projectName"
                class="search-item"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title">下达任务书</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <el-input
              v-model="queryForm.condition.studentName"
              clearable
              placeholder="输入学生学号、姓名搜索"
              style="width:200px"
              @keyup.enter.native="searchList"
            >
              <i
                slot="suffix"
                class="el-icon-search"
                style="margin-top:10px;cursor:pointer"
                @click="searchList"
              ></i>
            </el-input>
          </div>
          <div class="float-right">
            <el-button type="default" @click="exportFile()">{{$t('message.export')}}</el-button>
            <el-button type="primary" @click="addItem">新增任务书</el-button>
          </div>
        </div>
        <el-table
          :data="taskList"
          size="mini"
          style="width:100%"
          @selection-change="handleSelectionChange"
          tooltip-effect="light"
        >
          <el-table-column type="selection" stripe/>
          <el-table-column label="毕业年份" fixed="left">
            <template slot-scope="scope">{{ scope.row.grade }}</template>
          </el-table-column>
          <el-table-column label="课题名称" fixed="left" show-overflow-tooltip="true">
            <template slot-scope="scope">{{scope.row.projectName}}</template>
          </el-table-column>
          <el-table-column label="课题性质" fixed="left" show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.subjectProperties }}</template>
          </el-table-column>
          <el-table-column label="学生" fixed="left" show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.studentName }}</template>
          </el-table-column>
          <el-table-column label="行政学院" fixed="left" show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.facultyI18n }}</template>
          </el-table-column>
          <el-table-column label="专业" fixed="left" show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.subject }}</template>
          </el-table-column>
          <el-table-column label="方向" fixed="left" show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.direction }}</template>
          </el-table-column>
          <edu-table-column label="任务书状态" min-width="120">
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.status === 'WaitCommit' || scope.row.status === 'Recall'"
                type="info"
              >草稿
              </el-tag>
              <el-tag v-else-if="scope.row.status === 'Process'" type="info">待审核</el-tag>
              <el-tag v-else-if="scope.row.status === 'Reject'" type="danger">已驳回</el-tag>
              <el-tag v-else-if="scope.row.status === 'End'" type="success">已通过</el-tag>
            </template>
          </edu-table-column>
          <el-table-column :label="$t('label.operation')" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status === 'WaitCommit' || scope.row.status === 'Reject' || scope.row.status === 'Recall'"
                type="text"
                size="mini"
                @click="updateRecord(scope.row)"
              >{{$t("message.edit")}}
              </el-button>
              <el-button
                v-if="scope.row.status === 'Process'"
                type="text"
                size="mini"
                @click="callbackRecord(scope.row.flowNo, scope.row.grade)"
              >撤销
              </el-button>
              <el-button
                v-if="scope.row.status === 'End'"
                type="text"
                size="mini"
                @click="viewDetail(scope.row)"
              >查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="edu-pagination">
          <div class="float-right">
            <el-pagination
              :current-page="queryForm.pageNum_"
              :page-sizes="[20,50,100,500,1000]"
              :page-size="queryForm.pageSize_"
              :total="queryForm.total"
              layout="total, sizes, prev, pager, next, jumper"
              style="float: right;margin:10px 60px 0 0;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>
    <el-dialog
      :visible.sync="dialogConfig.visible"
      :title.sync="dialogConfig.title"
      width="40%"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
      style="margin-top:5%"
    >
      <el-form :model="dialogConfig.formData" label-width="130px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="毕业年份:">
              <el-date-picker
                class="search-item"
                clearable
                v-model="dialogConfig.formData.grade"
                @change="handleDialogGrade"
                value-format="yyyy"
                type="year"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="课题:">
              <el-select
                v-model="dialogConfig.formData.project"
                filterable
                class="search-item"
                clearable
              >
                <el-option
                  v-for="item in source.projectList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog(dialogConfig)">{{$t('message.cancel')}}</el-button>
                <el-button type="primary" @click="saveData">{{$t('message.confirm')}}</el-button>
            </span>
    </el-dialog>
    <div v-if="indexKey == 2">
      <TaskInfo
        ref="topicInfo"
        :subjectType="subjectType"
        :actionType="actionType"
        :basicInfoForm="taskInfoForm"
        :progressData="progressData"
        @topic-save="declareSave"
        @topic-cancel="declareCancel"
      ></TaskInfo>
    </div>
    <div v-if="indexKey == 3">
      <TaskInfo
        ref="topicInfo"
        :subjectType="subjectType"
        :actionType="actionType"
        :basicInfoForm="taskInfoForm"
        :progressData="progressData"
        @topic-save="declareSave"
        @topic-cancel="declareCancel"
      ></TaskInfo>
    </div>
    <div v-if="indexKey == 4">
      <TaskInfo
        ref="topicInfo"
        :subjectType="subjectType"
        :studentInfo="studentInfo"
        :actionType="actionType"
        :basicInfoForm="taskInfoForm"
        :progressData="progressData"
        @topic-save="declareSave"
        @topic-cancel="declareCancel"
      ></TaskInfo>
    </div>
  </div>
</template>
<script>
  import API from 'common/src/api/underGraduationDesign/reviewSubject'
  import {
    addData,
    editData,
    exportData,
    getExportStatus,
    getList,
    getSelectOpt,
    getSubjectType,
    recall,
    viewData
  } from 'common/src/api/underGraduationDesign/docTaskBook'
  import {approvelDetail} from 'common/src/api/approval'
  import tools from 'common/src/views/underGraduationDesign/tools.js';

  export default {
    name: 'taskBook',
    data() {
      return {
        api: API,
        queryForm: {
          pageNum_: 1,
          pageSize_: 20,
          condition: {
            grade: null,
            faculty: null,
            status: null,
            subjectProperties: null,
            projectName: null,
            studentName: null,
            subject: null
          }
        },
        taskInfoForm: {},
        studentInfo: {},
        taskList: [],
        indexKey: 1,
        breadPath: {
          label: '下达任务书',
          key: '1',
          children: [
            {
              key: '2',
              label: '新增任务书'
            },
            {
              key: '3',
              label: '编辑任务书'
            },
            {
              key: '4',
              label: '查看任务书'
            }
          ]
        },
        dialogConfig: {
          visible: false,
          title: '新增任务书',
          formData: {
            grade: null,
            project: null
          }
        },
        selectedData: [], // 勾选的列表数据
        actionType: '',
        subjectType: '',
        isEdit: false,
        currentStudent: '',
        progressData: [], //审核进度列表
        source: {
          studentColleges: [], // 行政学院
          subjectOptions: [], // 专业
          collegeOptions: [],
          projectList: [],
          statusOptions: [
            {
              label: '草稿',
              value: 'WaitCommit'
            },
            {
              label: '待审核',
              value: 'Process'
            },
            {
              label: '已驳回',
              value: 'Reject'
            },
            {
              label: '已通过',
              value: 'End'
            }
          ]
        }
      }
    },
    mounted() {
      this.queryForm.condition.grade = new Date().getFullYear() + '';
      this.getCollege()
      this.getSubjectNature()
      this.searchList()
      tools.initAllCollege(this.source.studentColleges);
    },
    methods: {
      handleSizeChange(size) {
        this.queryForm.pageSize_ = size;
        this.searchList()
      },
      handleCurrentChange(pageNum) {
        this.queryForm.pageNum_ = pageNum;
        this.searchList()
      },
      searchList() {
        getList(this.queryForm).then(res => {
          if (res.code == 200) {
            this.taskList = res.data.list
            this.queryForm.total = res.data.total
            this.selectedData = []
          }
        })
      },
      // 查课题性质
      getSubjectNature() {
        const params = {
          year: this.queryForm.condition.grade
        }
        this.api
        .getNature(params)
        .then(res => {
          this.source.subjectNatureOptions = res.data
        })
        .catch()
      },
      reset() {
        this.queryForm = {
          pageNum_: 1,
          pageSize_: 20,
          condition: {
            grade: null,
            faculty: null,
            status: null,
            subjectProperties: null,
            projectName: null,
            studentName: null,
            subject: null
          }
        }
        this.queryForm.condition.grade = new Date().getFullYear() + '';
        this.source.subjectOptions = []
        this.getSubjectNature();
        this.searchList()
      },
      handleSelectionChange(val) {
        this.selectedData = val
      },
      handleGradeChange(val) {
        this.queryForm.condition.subjectId = null
        this.source.subjectOptions = []
        if (val && this.queryForm.condition.faculty) {
          this.handleCollegeChange(this.queryForm.condition.faculty)
        }
        this.getSubjectNature();
        this.searchList();
      },
      // 查学院
      getCollege() {
        this.api.getCollege().then(res => {
          this.source.collegeOptions = res
        })
      },
      // 选择年份和学院查专业
      handleCollegeChange(val) {
        this.queryForm.condition.subjectId = ''
        this.source.subjectOptions = []
        if (val && this.queryForm.condition.grade) {
          const params = {
            grade: this.queryForm.condition.grade,
            college: val
          }
          this.api
          .getSubject(params)
          .then(res => {
            this.source.subjectOptions = res.data
          })
          .catch()
        }
      },
      handleDialogClose() {
        this.dialogConfig.visible = false
      },
      addItem() {
        this.isEdit = false
        this.currentStudent = ''
        this.dialogConfig.formData = {
          grade: null,
          project: null
        }
        this.dialogConfig.title = '新增任务书'
        this.dialogConfig.visible = true
      },
      handleDialogGrade(val) {
        getSelectOpt(val, this.currentStudent).then(res => {
          this.source.projectList = res.data
        })
      },
      closeDialog(dialogConfig) {
        dialogConfig.visible = false
      },
      saveData() {
        var code = this.dialogConfig.formData.project
        console.info(code)
        var strArray = code.split('_')
        if (this.isEdit) {
          getSubjectType(strArray[1]).then(res => {
            this.subjectType = res.data
          })
          this.actionType = 'EDIT'
          viewData(this.dialogConfig.formData.id).then(res => {
            this.taskInfoForm = res.data
            var projectList = this.source.projectList
            for (var i = 0; i < projectList.length; i++) {
              if (code == projectList[i].code) {
                this.taskInfoForm.projectName = projectList[i].name
                break
              }
            }
            this.taskInfoForm.proTotalId = strArray[0]
            if (strArray.length == 3) {
              this.taskInfoForm.subTitle = strArray[2]
            }
          })
          this.dialogConfig.visible = false
          this.indexKey = '3'
        } else {
          getSubjectType(strArray[1]).then(res => {
            this.subjectType = res.data
          })
          this.taskInfoForm = {}
          this.actionType = 'ADD'
          var projectList = this.source.projectList
          for (var i = 0; i < projectList.length; i++) {
            if (code == projectList[i].code) {
              this.taskInfoForm.projectName = projectList[i].name
              break
            }
          }
          this.taskInfoForm.proTotalId = strArray[0]
          if (strArray.length == 3) {
            this.taskInfoForm.subTitle = strArray[2]
          }
          this.dialogConfig.visible = false
          this.indexKey = '2'
        }
      },
      updateRecord(rowData) {
        this.isEdit = true
        var date = new Date()
        date.setFullYear(rowData.grade)
        this.dialogConfig.formData.grade = date
        this.dialogConfig.formData.project =
          rowData.proTotalId + '_' + rowData.studentId + '_' + rowData.subTitle
        this.currentStudent = rowData.studentId
        this.dialogConfig.formData.id = rowData.id
        getSelectOpt(rowData.grade, this.currentStudent).then(res => {
          this.source.projectList = res.data
        })
        this.dialogConfig.title = '编辑任务书'
        this.dialogConfig.visible = true
      },
      callbackRecord(flowNo, grade) {
        this.$eduConfirm('您确定要撤销吗？', '撤销').then(res => {
          recall(grade, flowNo).then(rs => {
            if (rs.code == 200) {
              this.searchList()
              this.$message({
                type: 'success',
                message: '撤销成功！'
              })
            } else {
              this.$message({
                type: 'warn',
                message: rs.message
              })
            }
          })
        })
      },
      viewDetail(row) {
        this.actionType = 'VIEW_TEACHER'
        viewData(row.id).then(res => {
          this.taskInfoForm = res.data
          this.studentInfo = {
            studentId: res.data.studentId,
            studentName: res.data.studentName,
            faculty: res.data.facultyI18n,
            subject: res.data.subject,
            direction: res.data.direction
          }
        })
        getSubjectType(row.studentId).then(res => {
          this.subjectType = res.data
        })
        approvelDetail({no: row.flowNo}).then(res => {
          if (res && res.data) {
            this.progressData = res.data.listApproveHistory
          }
        })
        this.indexKey = '4'
      },
      declareSave(params) {
        this.$refs.topicInfo.$refs['basicInfoForm'].validate(valid => {
          if (valid) {
            let promise = null
            if (params.actionType === 'EDIT') {
              promise = editData(params.data)
            } else {
              promise = addData(params.data)
            }
            promise
            .then(res => {
              this.$message.success('保存成功')
              this.indexKey = '1'
              this.searchList()
            })
            .catch()
          } else {
            return false
          }
        })
      },
      // 取消
      declareCancel() {
        this.indexKey = '1'
        this.searchList()
      },
      exportFile() {
        var params = {
          vo: this.queryForm.condition,
          list: this.selectedData
        }
        exportData(params).then(res => {
          // this.delayRequest(res.key)
          tools.downloadFile(res.key, "下达任务书.zip", getExportStatus, this);
        })
      },
      // 查文件导出状态，等待导出
      async delayRequest(key) {
        this.loading = true
        await new Promise(resolve => setTimeout(resolve, 3000))
        getExportStatus(key)
        .then(res => {
          this.loading = false
          if (res.code === 200 && res.data.status) {
            //let path = 'api/designservice/common/export?path=' + res.data.path
            let path =
              'api/designservice/resultPublish/downLoadMore?path=' +
              res.data.path +
              '&fileName=docTask.zip'
            window.open(path)
          } else {
            this.delayRequest(key)
          }
        })
        .catch(err => {
          this.loading = false
          this.delayRequest(key)
        })
      }
    },
    components: {
      TaskInfo: () => import('../components/taskInfo')
    }
  }
</script>

<style lang="scss" scoped>
  .review-topic {
    .search-item {
      width: 100%;
    }
  }
</style>
